package com.boot.shiro.util;

import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileUtil {
	
	private static Logger log = Logger.getLogger(FileUtil.class);
	
	/**
	 * NIO way
	 */
	public static byte[] toByteArray(String filename) {

		File f = new File(filename);
		if (!f.exists()) {
			log.error("文件未找到！" + filename);
			throw new RuntimeException("文件未找到！" + filename);
		}
		FileChannel channel = null;
		FileInputStream fs = null;
		try {
			fs = new FileInputStream(f);
			channel = fs.getChannel();
			ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
			while ((channel.read(byteBuffer)) > 0) {
				// do nothing
				// System.out.println("reading");
			}
			return byteBuffer.array();
		} catch (IOException e) {
			throw new RuntimeException("文件未找到或异常！" + filename);
		} finally {
			try {
				channel.close();
			} catch (IOException e) {
				throw new RuntimeException("文件未找到或异常！" + filename);
			}
			try {
				fs.close();
			} catch (IOException e) {
				throw new RuntimeException("文件未找到或异常！" + filename);
			}
		}
	}
	 public static String getFileUploadPath() {
	        //如果没有写文件上传路径,保存到临时目录
	        if(StringUtils.isEmpty(fileUploadPath)){
	            return ToolUtil.getTempPath();
	        }else{
	            //判断有没有结尾符,没有得加上
	            if(!fileUploadPath.endsWith(File.separator)){
	                fileUploadPath = fileUploadPath + File.separator;
	            }
	            //判断目录存不存在,不存在得加上
	            if(haveCreatePath == false){
	                File file = new File(fileUploadPath);
	                file.mkdirs();
	                haveCreatePath = true;
	            }
	            return fileUploadPath;
	        }
	    }
	    private static String fileUploadPath;
	    private static Boolean haveCreatePath = false;
}